package com.lee.boot.head.first.demo.mongo.dao.impl;


import com.lee.boot.head.first.demo.entity.Student;
import com.lee.boot.head.first.demo.mongo.dao.StudentDao;
import com.lee.boot.head.first.demo.mongo.dao.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author: Lee
 * @Date: 2018/10/26 10:50
 * @Description:
 */
@Repository
public class StudentDaoImpl implements StudentDao {

    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    StudentRepository studentRepository;

    /**
     * 生成一条记录
     *
     * @param student
     */
    @Override
    public void saveStudent(Student student) {
//        Student save = studentRepository.save(student);
        System.out.println(mongoTemplate.save(student));
    }


    /**
     * 修改一条记录 一个文档
     *
     * @param student
     */
    @Override
    public void updateStudent(Student student) {
        Query query = new Query(Criteria.where("name").is(student.getName()));
        Update update = new Update().set("name", student.getName()).set("age", student.getAge());

        System.out.println(mongoTemplate.updateFirst(query, update, Student.class));
    }

    /**
     * 根据id删除
     *
     * @param id
     */
    @Override
    public void deleteStudentById(Long id) {
        Query query = new Query(Criteria.where("id").is(id));
        System.out.println(mongoTemplate.remove(query, Student.class));
    }

    @Override
    public List<Student> getStudents() {
        List<Student> all = mongoTemplate.findAll(Student.class);
        return all;
    }
}
